<template>
  <div>
    <a-spin tip="Loading..." :spinning="isLoading">
      <div class="top">
        <div
          v-for="item,index in skuList"
          :key="item.pid"
          class="top-sku"
        >
          <a-checkbox
            class="top-sku-label"
            v-model:checked="item.checkAll"
            :indeterminate="item.indeterminate"
            @change="onSelectAll(item,index)"
          >
          {{ item.name }}:
          </a-checkbox>
          <a-checkbox-group class="sku-group" v-model:value="selectSku[index]" @change="onSelectItem(item,index)">
              <a-checkbox class="border" v-for="it in item.values" :value="it.vid">
                {{ it.name }}
              </a-checkbox>
          </a-checkbox-group>
        </div>
      </div>
      <chartView :commentSourceData="commentSourceData" :skuList="showDataList" v-model:is-loading="isLoading" />
      <base-table
          title="评论分析" 
          :scroll="{y:300}" 
          size="small" 
          :data-source="showDataList" 
          :columns="columns"
        >
      </base-table>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { RateList } from '../index/commentAnalysis';
import { skuType, Prop, tableDataType, selectSkuType, CompleteResult } from './sku';
import { ref } from 'vue';
import {TRequest} from "~/utils/ali/PCRequest";
import chartView from './chart.vue'
const props = defineProps<{
  id: number,
  commentSourceData: RateList[]
}>();
const columns = ref([
  {
    dataIndex: 'name',
    title: 'SKU',
    fixed: 'left',
  },
  {
    dataIndex: 'SKUID',
    title: 'SKUID',
    fixed: 'left',
  },
  {
    dataIndex: 'price',
    title: '价格',
  },
  {
    dataIndex: 'commentNumber',
    title: '评论条数',
  },
  {
    dataIndex: 'commentPercentage',
    title: '占比',
  },
])
const commentSourceData = ref<RateList[]>(props.commentSourceData)
const skuData = ref<skuType>()
const skuList = ref<(selectSkuType&Prop)[]>() // sku数据
const selectSku = ref<string[][]>([])
const dataList = ref<tableDataType[]>()// 表格原数据
const showDataList = ref<tableDataType[]>([])// 表格显示数据
const isLoading = ref(false)
// 获取数据
const getData = () => {
  isLoading.value = true
  TRequest.skuList(props.id).then(res => {
    skuData.value = res
    // 整理sku数据
    setSkuSelectList()
    // 初始化表格数据
    initData()
  })
}
// 整理sku数据
const setSkuSelectList = () => {
  skuList.value = skuData.value?.skuBase.props.map((item) => {
    selectSku.value.push([item.values[0].vid])
    return {
      ...item,
      indeterminate: true,
      checkAll: false,
    }
  })
}
// 全选单挑sku
const onSelectAll = (item: selectSkuType & Prop,index: number) => {
  if (item.checkAll) {
    selectSku.value[index] = item.values.map(item => item.vid)
    item.indeterminate = false
  }else {
    selectSku.value[index] = []
    item.indeterminate = false
  }
  updateShowStatus()
}
// 单选sku
const onSelectItem = (item: selectSkuType & Prop,index: number) => {
  if (selectSku.value[index].length === item.values.length) {
    item.checkAll = true
    item.indeterminate = false
  }else if (selectSku.value[index].length === 0) {
    item.checkAll = false
    item.indeterminate = false
  }else {
    item.checkAll = false
    item.indeterminate = true
  }
  updateShowStatus()
}
/**
 * 将以分号分隔的字符串转换为数组成对的列表
 * @param str - 要处理的字符串
 * @return 一个二维数组，其中每个内部数组包含两个数字
 */
const getSkuItemList = (str: string): number[][] => {
  return str.split(';').map(item => {
    return item.split(':').map(item => Number(item))
  })
}
/**
 * 设置数据名字的函数
 * @param skuList - 一个二维数组，包含键值对信息
 * @return 一个字符串，表示设置后的数据名字，如果没有有效数据则返回空字符串
 */
const setDataName = (skuList: number[][]): string => {
  let str = ''
  if (!skuData.value) return str = '-'
  for (let i = 0; i < skuData.value?.skuBase.props.length; i++) {
    const item = skuData.value?.skuBase.props[i];
    skuList.forEach(it => {
      if (Number(item.pid) == it[0]) {
        const vName = item.values.find(k => Number(k.vid) == it[1])?.name
        str += `${item.name}:${vName};`
      }
    })
  }
  return str.substr(0, str.length - 1)
}
/**
 * 根据产品 ID 设置数据价格的函数
 * @param skuId - 产品 ID
 * @return 产品价格，格式化为两位小数的字符串，如果找不到对应的价格则返回 0
 */
const setDataPrice = (skuId: string): number => {
  let price = 0
  const item = skuData.value?.skuCore.sku2info[skuId]
  if (!item) return price
  price =  parseFloat(Number(item.price.priceText).toFixed(2))
  return price
}
/**
 * 根据 skuId 计算评论数量的函数
 * @param skuId - 要统计的 SKU 标识符
 * @return skuId 在 commentSourceData 中出现的次数
 */
const setDataComment = (skuId: string): {commentNumber: number, commentArr: RateList[]} => {
  let commentNumber = 0
  const commentArr = [] as RateList[]
  commentSourceData.value.forEach(item => {
    if (item.skuId == skuId) {
      commentNumber++
      commentArr.push(item)
    }
  })
  return {
    commentNumber,
    commentArr
  }
}

/**
 * 根据 skuId 计算所有包含单挑Vid的数量
 * @param skuId - 要统计的 SKU 标识符
 * @return skuId 在 commentSourceData 中出现的次数
 */
const setDataSingleComment = (vid: string): {commentNumber: number, commentArr: RateList[]} => {
  let commentNumber = 0
  const commentArr = [] as RateList[]
  commentSourceData.value.forEach(item => {
    const strArr = item.skuVids ? item.skuVids.split('#') : []
    if (Array.isArray(strArr) && strArr.includes(vid)) {
      commentNumber++
      commentArr.push(item)
    }
  })
  return {
    commentNumber,
    commentArr
  }
}
/**
 * 生成所有可能的组合数据
 */
const generateCombinations = (): CompleteResult => {
  const singleCombinations: tableDataType[] = [];
  const allCombinations: tableDataType[] = [];

  // 生成单个组合
  skuData.value?.skuBase.props.forEach((item, index) => {
    item.values.forEach(value => {
      const comment = setDataSingleComment(value.vid)
      singleCombinations.push({
        name: `${item.name}: ${value.name}`,
        SKUID: '-',
        price: 0,
        commentNumber: comment.commentNumber,
        commentArr: comment.commentArr,
        commentPercentage: (comment.commentNumber / commentSourceData.value.length * 100).toFixed(0) + '%',
        isShow: false,
        propPath: `${item.pid}:${value.vid};`
      });
    });
  });
  // 生成全部组合
  const allSkuData = () => {
    skuData.value?.skuBase.skus.forEach(item => {
    const skuArr = getSkuItemList(item.propPath)
    const comment = setDataComment(item.skuId)
    allCombinations.push({
        name: setDataName(skuArr),
        SKUID: item.skuId,
        price: setDataPrice(item.skuId),
        commentNumber: comment.commentNumber,
        commentArr: comment.commentArr,
        commentPercentage: (comment.commentNumber / commentSourceData.value.length * 100).toFixed(0) + '%',
        isShow: false,
        propPath: item.propPath
      })
    })
  }
  allSkuData()
  return {
    singleCombinations,
    allCombinations
  };
}

// 初始化表格数据
const initData = () => {
  const { singleCombinations, allCombinations } = generateCombinations()
  dataList.value = [...singleCombinations, ...allCombinations]
  updateShowStatus()
}

// 设置显示数据
const setShowData = () => {
  if (Array.isArray(dataList.value)) {
    showDataList.value = dataList.value.filter(item => item.isShow)
    console.log("🚀 ~ setShowData ~ showDataList.value:", showDataList.value)    
  }
}

// 更新数据
const updateShowStatus = (): void => {
   /**
   * 生成所有可能的组合数据
   * @param arrays - 多维数组，其中每个元素都是一个字符串数组
   * @param index - 当前递归的索引，表示正在处理 arrays 中的第几个数组
   * @param currentCombination - 当前的组合结果
   * @return 所有可能的组合结果，以二维数组形式返回
   */
  const generateCombinations = (arrays: string[][], index: number, currentCombination: string[]): string[][] => {
    if (index === arrays.length) {
      return [currentCombination];
    }
    const result: string[][] = [];
    if (arrays[index].length === 0) {
      result.push(...generateCombinations(arrays, index + 1, [...currentCombination]));
    } else {
      for (const value of arrays[index]) {
        result.push(...generateCombinations(arrays, index + 1, [...currentCombination, value]));
      }
    }
    return result;
  }
  const allCombinations = generateCombinations(selectSku.value, 0, []);
  dataList.value?.forEach(item => {
    const propPathPairs = item.propPath.split(';').filter(Boolean);
    const propPathValues = propPathPairs.map(pair => pair.split(':')[1]);
    let matchesAnyCombination = false;
    // 单一匹配
    if (propPathValues.length === 1) {
      matchesAnyCombination = allCombinations.some(combination =>
        combination.includes(propPathValues[0])
      );
    } else {
      // 全额匹配
      matchesAnyCombination = allCombinations.some(combination =>
        propPathValues.every(value => combination.includes(value))
      );
    }
    item.isShow = matchesAnyCombination;
  })
  setShowData()
}

const init = () => {
  getData()
}
init()
</script>

<style lang="less" scoped>
.top {
  height: 200px;
  overflow: hidden auto;
  &-sku {
    margin-bottom: 20px; 
    display: flex;
    align-items: flex-start;
    &-label {
      margin-right: 5px;
      ::v-deep .xc-ant-checkbox {
        height: 100%;
      }
    }
    .sku-group {
      flex: 1;
      ::v-deep .xc-ant-checkbox-wrapper-checked   {
        border: 1px solid #409eff !important;
      }
      .border {
        padding: 5px 10px;
        border: 1px solid #dcdfe6;
        margin-bottom: 5px;
      }
    }
  }
}
</style>